/**
 * Copyright (C) 2012 Eduard Sedov
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.es.eventbus;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author Sedov Eduard
 */
public class EventBus {

    private static EventBus instance = new EventBus();
    /**
     * Holds EventListeners, TopicListeners or WeakReference to them. The key is
     * either a class or a string.
     */
    private Map<Object, List> listeners = new HashMap();

    public static EventBus get() {
        return instance;
    }

    public void subscribe(Class eventClass, EventListener listener) {
        subscribe_intern(new WeakReference(listener), eventClass);
    }

    public void subscribeStrong(Class eventClass, EventListener listener) {
        subscribe_intern(listener, eventClass);
    }

    public void subscribe(String topic, TopicListener listener) {
        subscribe_intern(new WeakReference(listener), topic);
    }

    public void subscribeStrong(String topic, TopicListener listener) {
        subscribe_intern(listener, topic);
    }

    private synchronized void subscribe_intern(Object listener, Object eventClassOrTopic) {
        if (listener == null) {
            return;
        }

        List listenersList = listeners.get(eventClassOrTopic);

        if (listenersList == null) {
            listenersList = new ArrayList();
            listeners.put(eventClassOrTopic, listenersList);
            listenersList.add(listener);
        } else {
            for (int i = 0; i < listenersList.size(); i++) {
                Object item = listenersList.get(i);
                if (item == listener || item instanceof WeakReference && ((WeakReference) item).get() == listener) {
                    return;
                }
            }
            listenersList.add(listener);
        }
    }

    public void unsubscribe(Class eventClass, EventListener listener) {
        unsubscribe_intern(eventClass, listener);
    }

    public void unsubscribe(String topic, TopicListener listener) {
        unsubscribe_intern(topic, listener);
    }

    private synchronized void unsubscribe_intern(Object eventClassOrTopic, Object listener) {
        List listenersList = listeners.get(eventClassOrTopic);

        if (listenersList == null) {
            return;
        }

        for (int i = 0; i < listenersList.size(); i++) {
            Object item = listenersList.get(i);
            if (item == listener || item instanceof WeakReference && ((WeakReference) item).get() == listener) {
                listenersList.remove(i);
                return;
            }
        }
    }

    public void publish(Object event) {
        publish_intern(event == null ? null : event.getClass(), event);
    }

    public void publish(String topic, Object event) {
        publish_intern(topic, event);
    }

    private synchronized void publish_intern(Object eventClassOrTopic, Object event) {
        List listenersList = listeners.get(eventClassOrTopic);

        if (listenersList == null || listenersList.isEmpty()) {
            if (eventClassOrTopic instanceof Class) {
                event = new DeadEvent(event);
                listenersList = listeners.get(event.getClass());
            } else if (eventClassOrTopic instanceof String) {
                event = new DeadTopicEvent(eventClassOrTopic.toString(), event);
                listenersList = listeners.get(event.getClass());
            }
        }

        if (listenersList == null) {
            return;
        }

        for (int i = 0; i < listenersList.size(); i++) {
            Object item = listenersList.get(i);
            if (item instanceof WeakReference) {
                item = ((WeakReference) item).get();
            }
            if (item == null) {
                listenersList.remove(i);
                i--;
            } else if (item instanceof EventListener) {
                callListener(event, (EventListener) item);
            } else if (item instanceof TopicListener) {
                callListener(eventClassOrTopic == null ? null : eventClassOrTopic.toString(), event, (TopicListener) item);
            }
        }
    }

    protected void callListener(Object event, EventListener listener) {
        listener.onEvent(event);
    }

    protected void callListener(String topic, Object event, TopicListener listener) {
        listener.onEvent(topic, event);
    }

    public synchronized List<? extends EventListener> getEventListener(Class eventClass) {
        List result = new ArrayList();

        List listenersList = listeners.get(eventClass);

        if (listenersList == null) {
            return result;
        }

        for (int i = 0; i < listenersList.size(); i++) {
            Object item = listenersList.get(i);
            if (item instanceof WeakReference) {
                item = ((WeakReference) item).get();
            }
            if (item == null) {
                listenersList.remove(i);
                i--;
            } else {
                result.add(item);
            }
        }

        return result;
    }
}
